package com.example.stockholdtrack

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.stockholdtrack.data.StockDataStore
import com.example.stockholdtrack.data.StockItem
import com.example.stockholdtrack.ui.StockViewModel
import com.example.stockholdtrack.ui.theme.StockHoldTrackTheme


class MainActivity : ComponentActivity() {
    private lateinit var dataStore: StockDataStore
    private var shouldRefreshOnResume = false
    private var refreshTrigger = 0
    private lateinit var stockViewModel: StockViewModel
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // 初始化数据存储
        dataStore = StockDataStore(this)
        
        setContent {
            StockHoldTrackTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    StockListScreen(
                        modifier = Modifier.padding(innerPadding),
                        dataStore = dataStore,
                        shouldRefresh = shouldRefreshOnResume,
                        refreshTrigger = refreshTrigger,
                        onRefreshComplete = { shouldRefreshOnResume = false },
                        onViewModelCreated = { viewModel -> 
                            stockViewModel = viewModel 
                            // onCreate时请求一次股价
                            viewModel.requestStockPrices()
                        },
                        onAddStockClick = {
                            // 跳转到搜索页面
                            val intent = android.content.Intent(this, StockSearchActivity::class.java)
                            startActivityForResult(intent, 1002)
                        }
                    )
                }
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        shouldRefreshOnResume = true
        // 当从详情页返回时，重新计算数据并请求股价
        if (::stockViewModel.isInitialized) {
            stockViewModel.refreshStocks()
            stockViewModel.requestStockPrices()
        }
    }
    
    override fun onPause() {
        super.onPause()
    }
    
    override fun onStop() {
        super.onStop()
    }
    
    override fun onDestroy() {
        super.onDestroy()
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: android.content.Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001 && resultCode == android.app.Activity.RESULT_OK) {
            shouldRefreshOnResume = true
            refreshTrigger = refreshTrigger + 1
            if (::stockViewModel.isInitialized) {
                stockViewModel.requestStockPrices()
            }
        } else if (requestCode == 1002 && resultCode == android.app.Activity.RESULT_OK && data != null) {
            // 处理搜索页面返回的股票选择结果
            val stockCode = data.getStringExtra("stock_code") ?: ""
            val stockName = data.getStringExtra("stock_name") ?: ""
            
            if (stockCode.isNotBlank() && stockName.isNotBlank()) {
                println("DEBUG: MainActivity.onActivityResult - 从搜索页面返回股票: $stockName ($stockCode)")
                
                // 添加新股票到数据库
                val newStock = StockItem(
                    name = stockName,
                    code = stockCode,
                    averagePrice = 0.0,
                    currentPrice = 0.0,
                    quantity = 0
                )
                
                if (::stockViewModel.isInitialized) {
                    stockViewModel.addStock(newStock)
                    println("DEBUG: MainActivity.onActivityResult - 成功添加股票: $stockName")
                }
            }
        }
    }
}



@OptIn(ExperimentalMaterialApi::class)
@Composable
fun StockListScreen(
    modifier: Modifier = Modifier,
    dataStore: StockDataStore,
    shouldRefresh: Boolean = false,
    refreshTrigger: Int = 0,
    onRefreshComplete: () -> Unit = {},
    onViewModelCreated: (StockViewModel) -> Unit = {},
    onAddStockClick: () -> Unit = {}
) {
    var showAddDialog by remember { mutableStateOf(false) }
    
    val viewModel: StockViewModel = viewModel(
        factory = StockViewModel.Factory(dataStore)
    )
    
    // 通知父组件ViewModel已创建
    LaunchedEffect(viewModel) {
        onViewModelCreated(viewModel)
    }
    
    val stocks by viewModel.stocks.collectAsStateWithLifecycle()
    val isLoading by viewModel.isLoading.collectAsStateWithLifecycle()
    
    // 下拉刷新状态
    var isRefreshing by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullRefreshState(
        refreshing = isRefreshing,
        onRefresh = {
            println("DEBUG: MainActivity.pullRefreshState - 触发下拉刷新")
            isRefreshing = true
            viewModel.requestStockPrices()
        }
    )
    
    // 监听刷新标志，当shouldRefresh为true时重新加载数据
    androidx.compose.runtime.LaunchedEffect(shouldRefresh) {
        println("DEBUG: MainActivity.LaunchedEffect - 触发 - shouldRefresh: $shouldRefresh")
        if (shouldRefresh) {
            println("DEBUG: MainActivity.LaunchedEffect - 触发数据刷新")
            viewModel.refreshStocks()
            onRefreshComplete()
        }
    }
    
    // 额外的刷新机制：监听onActivityResult和onResume的调用
    androidx.compose.runtime.LaunchedEffect(refreshTrigger) {
        if (refreshTrigger > 0) {
            println("DEBUG: MainActivity.LaunchedEffect - 通过refreshTrigger触发数据刷新")
            viewModel.refreshStocks()
        }
    }
    
    // 监听股票数据变化，确保UI更新并重置下拉刷新状态
    androidx.compose.runtime.LaunchedEffect(stocks) {
        println("DEBUG: MainActivity.LaunchedEffect - 股票数据更新 - 数量: ${stocks.size}")
        stocks.forEachIndexed { index, stock ->
            println("DEBUG: MainActivity.LaunchedEffect - 股票[$index]: ${stock.name} (${stock.code}) - 持仓: ${stock.quantity}股, 均价: ${stock.averagePrice}")
        }
    }
    
    // 监听加载状态变化，结束下拉刷新
    androidx.compose.runtime.LaunchedEffect(isLoading) {
        if (!isLoading && isRefreshing) {
            println("DEBUG: MainActivity.LaunchedEffect - 加载完成，结束下拉刷新")
            isRefreshing = false
        }
    }
    
    // 新增：专门监听下拉刷新状态，确保在股价请求完成后重置
    androidx.compose.runtime.LaunchedEffect(stocks, isLoading) {
        if (isRefreshing && !isLoading) {
            println("DEBUG: MainActivity.LaunchedEffect - 股价请求完成，重置下拉刷新状态")
            isRefreshing = false
        }
    }
    
    Column(modifier = modifier.fillMaxSize()) {
        // 顶部标题栏
        Surface(
            modifier = Modifier.fillMaxWidth(),
            color = Color(0xFFE53935), // 红色背景
            shadowElevation = 4.dp
        ) {
            Text(
                text = "我的持仓",
                modifier = Modifier.padding(16.dp),
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
        }
        
        // 股票列表（带下拉刷新）
        if (isLoading && !isRefreshing) {
            Box(
                modifier = Modifier.weight(1f),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else {
            Box(
                modifier = Modifier
                    .weight(1f)
                    .pullRefresh(pullRefreshState)
            ) {
                LazyColumn(
                    contentPadding = PaddingValues(vertical = 8.dp)
                ) {
                    items(stocks, key = { it.id }) { stock ->
                        StockListItem(
                            stock = stock,
                            onDelete = { stockToDelete ->
                                viewModel.deleteStock(stockToDelete)
                            }
                        )
                    }
                }
                
                // 下拉刷新指示器
                PullRefreshIndicator(
                    refreshing = isRefreshing,
                    state = pullRefreshState,
                    modifier = Modifier.align(Alignment.TopCenter),
                    backgroundColor = Color.White,
                    contentColor = Color(0xFFE53935)
                )
            }
        }
        
        // 底部新建按钮
        Surface(
            modifier = Modifier.fillMaxWidth(),
            color = Color.White,
            shadowElevation = 8.dp
        ) {
            Button(
                onClick = { onAddStockClick() },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFE53935)
                ),
                shape = RoundedCornerShape(8.dp)
            ) {
                Text(
                    text = "新建股票",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
            }
        }
    }
}

@Composable
fun AddStockDialog(
    onDismiss: () -> Unit,
    onConfirm: (String, String) -> Unit
) {
    var stockName by remember { mutableStateOf("") }
    var stockCode by remember { mutableStateOf("") }
    
    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 标题
                Text(
                    text = "新建股票",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                
                // 股票名称输入框
                OutlinedTextField(
                    value = stockName,
                    onValueChange = { stockName = it },
                    label = { Text("股票名称") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )
                
                // 股票代码输入框
                OutlinedTextField(
                    value = stockCode,
                    onValueChange = { stockCode = it },
                    label = { Text("股票代码") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                )
                
                // 按钮行
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 取消按钮
                    OutlinedButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("取消")
                    }
                    
                    // 确认按钮
                    Button(
                        onClick = { 
                            if (stockName.isNotBlank() && stockCode.isNotBlank()) {
                                onConfirm(stockName, stockCode)
                            }
                        },
                        modifier = Modifier.weight(1f),
                        enabled = stockName.isNotBlank() && stockCode.isNotBlank()
                    ) {
                        Text("确认")
                    }
                }
            }
        }
    }
}

@Composable
fun StockListItem(
    stock: StockItem,
    onDelete: (StockItem) -> Unit
) {
    val context = androidx.compose.ui.platform.LocalContext.current
    var showDeleteDialog by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 4.dp)
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = {
                        // 跳转到详情页面
                        val intent = android.content.Intent(context, StockDetailActivity::class.java).apply {
                            putExtra("stock_code", stock.code)
                        }
                        // 使用startActivityForResult来获取返回结果
                        (context as? androidx.activity.ComponentActivity)?.startActivityForResult(
                            intent, 
                            1001
                        ) ?: context.startActivity(intent)
                    },
                    onLongPress = {
                        showDeleteDialog = true
                    }
                )
            },
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧：股票信息
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = stock.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.Black
                )
                Text(
                    text = stock.code,
                    fontSize = 12.sp,
                    color = Color.Gray
                )
                // 添加持仓数量信息
                Text(
                    text = "持仓: ${stock.quantity}股",
                    fontSize = 11.sp,
                    color = Color.Gray
                )
            }
            
            // 右侧：价格信息
            Column(
                horizontalAlignment = Alignment.End,
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                // 实时价格（显示在均价上方）
                if (stock.currentPrice > 0) {
                    Text(
                        text = "¥${String.format("%.2f", stock.currentPrice)}",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFFE53935) // 红色价格
                    )
                }
                
                // 持仓均价
                Text(
                    text = "均价: ¥${String.format("%.2f", stock.averagePrice)}",
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFFE53935) // 红色均价
                )
                
                // 总市值（使用实时价格计算）
                val marketValue = if (stock.currentPrice > 0) stock.currentPrice * stock.quantity else stock.averagePrice * stock.quantity
                Text(
                    text = "市值: ¥${String.format("%.2f", marketValue)}",
                    fontSize = 12.sp,
                    color = Color.Gray
                )
            }
        }
    }
    
    // 删除确认对话框
    if (showDeleteDialog) {
        DeleteStockDialog(
            stock = stock,
            onDismiss = { showDeleteDialog = false },
            onConfirm = { stockToDelete ->
                onDelete(stockToDelete)
                showDeleteDialog = false
            }
        )
    }
}

@Composable
fun DeleteStockDialog(
    stock: StockItem,
    onDismiss: () -> Unit,
    onConfirm: (StockItem) -> Unit
) {
    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 标题
                Text(
                    text = "删除股票",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                
                // 检查持仓数量
                if (stock.quantity > 0) {
                    // 有持仓，显示警告信息
                    Text(
                        text = "无法删除股票 \"${stock.name}\"",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFFE53935) // 红色警告
                    )
                    Text(
                        text = "该股票还有 ${stock.quantity} 股持仓，请先清空持仓后再删除。",
                        fontSize = 14.sp,
                        color = Color.Gray
                    )
                    
                    // 只有确定按钮
                    Button(
                        onClick = onDismiss,
                        modifier = Modifier.fillMaxWidth(),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFFE53935)
                        )
                    ) {
                        Text("确定")
                    }
                } else {
                    // 无持仓，可以删除
                    Text(
                        text = "确定要删除股票 \"${stock.name}\" 吗？",
                        fontSize = 16.sp,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    Text(
                        text = "删除后将无法恢复。",
                        fontSize = 14.sp,
                        color = Color.Gray
                    )
                    
                    // 按钮行
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // 取消按钮
                        OutlinedButton(
                            onClick = onDismiss,
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("取消")
                        }
                        
                        // 确认删除按钮
                        Button(
                            onClick = { onConfirm(stock) },
                            modifier = Modifier.weight(1f),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFFE53935)
                            )
                        ) {
                            Text("删除")
                        }
                    }
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun StockListScreenPreview() {
    StockHoldTrackTheme {
        // Preview需要模拟数据存储
        // StockListScreen()
    }
}